'use client'

import { useState, useEffect } from 'react'
import { XMarkIcon, UserPlusIcon, UserMinusIcon } from '@heroicons/react/24/outline'

interface User {
  id: number
  name: string
  email: string
  color: string
  avatar?: string
}

interface Project {
  id: number
  name: string
  description: string
  isArchived: boolean
  created_at: string
}

interface NewProjectModalProps {
  isOpen: boolean
  onClose: () => void
  onSuccess: () => void
  editMode?: boolean
  project?: Project | null
  initialMembers?: User[]
}

export default function NewProjectModal({ 
  isOpen, 
  onClose, 
  onSuccess, 
  editMode = false, 
  project = null,
  initialMembers = []
}: NewProjectModalProps) {
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<User[]>([])
  const [selectedMembers, setSelectedMembers] = useState<User[]>([])
  const [searchLoading, setSearchLoading] = useState(false)
  const [currentUser, setCurrentUser] = useState<User | null>(null)

  useEffect(() => {
    if (isOpen) {
      if (editMode && project) {
        // 编辑模式：加载现有项目数据
        setName(project.name)
        setDescription(project.description)
        if (initialMembers?.length > 0) {
          setSelectedMembers(initialMembers)
        }
      } else {
        // 创建模式：获取当前用户信息
        fetchCurrentUser()
      }
    } else {
      // 重置表单
      setName('')
      setDescription('')
      setSearchQuery('')
      setSearchResults([])
      setSelectedMembers([])
      setError('')
    }
  }, [isOpen, editMode, project])

  useEffect(() => {
    if (searchQuery) {
      const timer = setTimeout(() => {
        searchUsers()
      }, 300) // 防抖300ms
      return () => clearTimeout(timer)
    } else {
      setSearchResults([])
    }
  }, [searchQuery])

  const fetchCurrentUser = async () => {
    try {
      const response = await fetch('/api/user/me')
      if (response.ok) {
        const user = await response.json()
        setCurrentUser(user)
        // 自动将当前用户添加为成员
        setSelectedMembers([user])
      } else {
        const errorData = await response.json()
        if (errorData.casdoorError) {
          // Casdoor相关错误，显示用户友好的错误信息
          alert(`认证服务暂时不可用：${errorData.error}\n\n请检查网络连接或联系管理员。`)
          // 关闭模态框并重定向到登录页面
          onClose()
          window.location.href = '/auth/login'
        } else {
          // 其他错误
          console.error('获取当前用户失败:', errorData.error)
        }
      }
    } catch (err) {
      console.error('获取当前用户失败:', err)
      // 网络错误或其他异常
      alert('无法连接到服务器，请检查网络连接后重试。')
    }
  }

  const searchUsers = async () => {
    setSearchLoading(true)
    try {
      const response = await fetch(`/api/users/search?q=${encodeURIComponent(searchQuery)}`)
      if (response.ok) {
        const users = await response.json()
        // 过滤掉已选择的成员
        const filteredUsers = users.filter((user: User) => 
          !selectedMembers.some(member => member.id === user.id)
        )
        setSearchResults(filteredUsers)
      }
    } catch (err) {
      console.error('搜索用户失败:', err)
    } finally {
      setSearchLoading(false)
    }
  }

  const addMember = (user: User) => {
    setSelectedMembers([...selectedMembers, user])
    setSearchResults(searchResults.filter(u => u.id !== user.id))
  }

  const removeMember = (userId: number) => {
    // 在编辑模式下，不能在Modal中移除成员（需要在项目页面操作）
    if (editMode) {
      return
    }
    // 不能移除创建者（当前用户）
    if (currentUser && userId === currentUser.id) {
      return
    }
    setSelectedMembers(selectedMembers.filter(member => member.id !== userId))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)
    setError('')

    try {
      if (editMode && project) {
        // 编辑模式：更新项目信息和成员
        const response = await fetch(`/api/projects/${project.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            description,
            memberIds: selectedMembers.map(m => m.id)
          }),
        })

        if (response.ok) {
          onSuccess()
          onClose()
        } else {
          const data = await response.json()
          setError(data.error || '更新项目失败')
        }
      } else {
        // 创建模式
        const response = await fetch('/api/projects', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            name, 
            description,
            memberIds: selectedMembers.map(m => m.id)
          }),
        })

        if (response.ok) {
          const project = await response.json()
          onSuccess()
          // 跳转到新项目的todolist页面
          window.location.href = `/${encodeURIComponent(project.name)}/todolist`
        } else {
          const data = await response.json()
          setError(data.error || '创建项目失败')
        }
      }
    } catch (err) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity z-50">
      <div className="fixed inset-0 z-50 overflow-y-auto">
        <div className="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
          <div className="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all sm:my-8 sm:w-full sm:max-w-lg">
            <form onSubmit={handleSubmit}>
              <div className="bg-white px-4 pb-4 pt-5 sm:p-6 sm:pb-4">
                <div className="sm:flex sm:items-start">
                  <div className="mt-3 text-center sm:ml-4 sm:mt-0 sm:text-left w-full">
                    <div className="flex justify-between items-center mb-4">
                      <h3 className="text-lg font-semibold leading-6 text-gray-900">
                        {editMode ? '项目管理' : '新建项目'}
                      </h3>
                      <button
                        type="button"
                        onClick={onClose}
                        className="rounded-md bg-white text-gray-400 hover:text-gray-500"
                      >
                        <XMarkIcon className="h-6 w-6" />
                      </button>
                    </div>
                    
                    {error && (
                      <div className="mb-4 rounded-md bg-red-50 p-4">
                        <p className="text-sm text-red-800">{error}</p>
                      </div>
                    )}

                    <div className="mt-4">
                      <label htmlFor="project-name" className="block text-sm font-medium text-gray-700">
                        项目名称
                      </label>
                      <input
                        type="text"
                        id="project-name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm px-3 py-2 border"
                        placeholder="输入项目名称"
                        required
                        maxLength={50}
                        disabled={editMode} // 编辑模式下不允许修改项目名称
                      />
                    </div>

                    <div className="mt-4">
                      <label htmlFor="project-description" className="block text-sm font-medium text-gray-700">
                        项目简介
                      </label>
                      <textarea
                        id="project-description"
                        value={description}
                        onChange={(e) => setDescription(e.target.value)}
                        rows={3}
                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm px-3 py-2 border"
                        placeholder="输入项目简介"
                        required
                        maxLength={300}
                      />
                      <p className="mt-1 text-sm text-gray-500">
                        {description.length}/300 字符
                      </p>
                    </div>

                    <div className="mt-4">
                      <label className="block text-sm font-medium text-gray-700">
                        项目成员
                      </label>
                      
                      {/* 已选择的成员 */}
                      <div className="mt-2 space-y-2">
                        {selectedMembers.map((member) => (
                          <div key={member.id} className="flex items-center justify-between bg-gray-50 rounded-md px-3 py-2">
                            <div className="flex items-center">
                              <div
                                className="w-8 h-8 rounded-full mr-3"
                                style={{ backgroundColor: member.color }}
                              ></div>
                              <div>
                                <p className="text-sm font-medium text-gray-900">{member.name}</p>
                                <p className="text-xs text-gray-500">{member.email}</p>
                              </div>
                            </div>
                            {editMode ? (
                              <span className="text-xs text-gray-500">在项目页面移除</span>
                            ) : (
                              currentUser && member.id !== currentUser.id && (
                                <button
                                  type="button"
                                  onClick={() => removeMember(member.id)}
                                  className="text-red-600 hover:text-red-800"
                                >
                                  <UserMinusIcon className="h-5 w-5" />
                                </button>
                              )
                            )}
                            {!editMode && currentUser && member.id === currentUser.id && (
                              <span className="text-xs text-gray-500">创建者</span>
                            )}
                          </div>
                        ))}
                      </div>

                      {/* 搜索用户 - 在创建和编辑模式下都显示 */}
                      <div className="mt-3">
                        <input
                          type="text"
                          value={searchQuery}
                          onChange={(e) => setSearchQuery(e.target.value)}
                          className="block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm px-3 py-2 border"
                          placeholder="搜索用户名或邮箱添加成员..."
                        />
                        
                        {searchLoading && (
                          <p className="mt-2 text-sm text-gray-500">搜索中...</p>
                        )}

                        {searchResults.length > 0 && (
                          <div className="mt-2 max-h-40 overflow-y-auto border border-gray-200 rounded-md">
                            {searchResults.map((user) => (
                              <div
                                key={user.id}
                                className="flex items-center justify-between p-2 hover:bg-gray-50 cursor-pointer"
                                onClick={() => addMember(user)}
                              >
                                <div className="flex items-center">
                                  <div
                                    className="w-6 h-6 rounded-full mr-2"
                                    style={{ backgroundColor: user.color }}
                                  ></div>
                                  <div>
                                    <p className="text-sm font-medium text-gray-900">{user.name}</p>
                                    <p className="text-xs text-gray-500">{user.email}</p>
                                  </div>
                                </div>
                                <UserPlusIcon className="h-5 w-5 text-green-600" />
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="bg-gray-50 px-4 py-3 sm:flex sm:flex-row-reverse sm:px-6">
                <button
                  type="submit"
                  disabled={loading || (!editMode && selectedMembers.length === 0)}
                  className="inline-flex w-full justify-center rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 sm:ml-3 sm:w-auto disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {loading ? (editMode ? '更新中...' : '创建中...') : (editMode ? '更新项目' : '创建项目')}
                </button>
                <button
                  type="button"
                  onClick={onClose}
                  disabled={loading}
                  className="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 sm:mt-0 sm:w-auto"
                >
                  取消
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
} 